package com.eastdigit.system.controller;

import com.eastdigit.servlet.*;
import com.eastdigit.system.model.Role;
import com.eastdigit.system.service.IDataScopeService;
import com.eastdigit.system.service.IRoleService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IDataScopeService dataScopeService;

    @RequestMapping(value = "/query")
    @ResponseBody
    @DeptPermPrepare(id = "roleId", deptId = "deptId")
    public JSONObject queryRole(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        return Response.response(roleService.queryTable(reqBean));
    }

    @RequestMapping(value = "/tree")
    @ResponseBody
    @DeptPermPrepare(id = "roleId", deptId = "deptId")
    public JSONObject queryRoleTree(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        return Response.response(roleService.queryRoleTree(reqBean.getUserId()));
    }

    @RequestMapping(value = "/add")
    @ResponseBody
    @DeptPermValidate(id = "roleId", deptId = "deptId")
    public JSONObject addRole(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        roleService.add(getRole(reqBean));
        return Response.responseSuccess();
    }

    @RequestMapping(value = "/update")
    @ResponseBody
    @DeptPermValidate(id = "roleId", deptId = "deptId")
    public JSONObject updateRole(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        roleService.update(getRole(reqBean));
        return Response.responseSuccess();
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    @DeptPermValidate(id = "roleId", deptId = "deptId")
    public JSONObject removeRole(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        roleService.delete(reqBean.getInfo("roleId"));
        return Response.responseSuccess();
    }

    @RequestMapping(value = "/reloadDataScope")
    @ResponseBody
    public JSONObject reloadDataScope() {
        dataScopeService.reload();
        return Response.responseSuccess();
    }

    /**
     * 从表单获取对象
     * 
     * @param reqBean
     * @return
     */
    private Role getRole(ReqBean reqBean) {
        Role role = new Role();
        role.setId(reqBean.getInfo("roleId"));
        role.setDeptId(reqBean.getInfo("deptId"));
        role.setName(reqBean.getInfo("roleName"));
        role.setScope(reqBean.getInfo("roleScope"));
        role.setOperator(reqBean.getUserId());
        role.setRemark(reqBean.getInfo("remark"));
        return role;
    }

}
